export function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function savePicToAlbum (tempFilePath, that) {
  // let that = this;
  wx.getSetting({
    success (res) {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success () {
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success (res) {
                wx.hideLoading();
                wx.showModal({
                  title: '提交生成',
                  content: '日历图片已经保存到手机，去分享到朋友圈吧~',
                  confirmText: '确认',
                  confirmColor: '#3CC51F',
                  showCancel: false,
                  success: function (res) {
                    that.canvasShow = false;
                  }
                });
              },
              fail (res) {
                console.log(res);
                wx.hideLoading();
              }
            })
          },
          fail () {
            that.canvasShow = false;
            wx.hideLoading();
            // 用户拒绝授权,打开设置页面
            wx.openSetting({
              success: function (data) {
                console.log("openSetting: success");
              },
              fail: function (data) {
                console.log("openSetting: fail");
              }
            });
          }
        })
      } else {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success (res) {
            // that.canvasShow = false;

            wx.hideLoading();
            wx.showModal({
              title: '提交生成',
              content: '日历图片已经保存到手机，去分享到朋友圈吧~',
              confirmText: '确认',
              confirmColor: '#3CC51F',
              showCancel: false,
              success: function (res) {
                that.canvasShow = false;
              }
            });
          },
          fail (res) {
            wx.hideLoading();
            that.canvasShow = false;
            console.log(res);
          }
        })
      }
    },
    fail (res) {
      wx.hideLoading();
      console.log(res);
    }
  })
}

